import 'dart:async';
import 'dart:convert';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;
import 'package:smart_translator/app/db/DbDAOHelper.dart';
import 'package:smart_translator/app/event/DataCallBack.dart';
import 'package:smart_translator/app/views/controller/IndexViewController.dart';
import '../../../const/AppConst.dart';
import '../../../db/database.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../services/AudioService.dart';
import '../../../style/widget_style.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/tips.dart';
import '../../IndexTranslation/controllers/index_translation_controller.dart';
import 'package:web_socket_client/web_socket_client.dart' as ws;


class TranslateResultController extends GetxController {

 /* var transContent = ''.obs;
  var translateResult = '正在翻译...'.obs;*/
  String? taskId;

  AudioService audioService = Get.find<AudioService>();

  RxList<TranslationHistoryData> historyData = RxList();
  RxList<Widget>  historyWigetItem = RxList();

  ScrollController listScroll = ScrollController();

  var autoSpeakWbSocket;
  Uint8List audioData =  Uint8List(0);
  Timer? ttsWsTimer;

  AudioPlayer? player;

  @override
  void onInit() {
    super.onInit();
    // transContent.value = Get.parameters['content']!;
  }


  void initTTsWbSocket(DataCallBack callBack) async {
    stopTTSWs();
    autoSpeakWbSocket = ws.WebSocket (Uri.parse('wss://${NetWorkManager.WS_IP + NetWorkManager.TTS_REALTIME}'),
        headers: {
          'x-api-key': '264e03da4958e5ea405dd8f63b87da898757b821',
          // 'x-app-id': 'RquRazmzJpXLdp84'
        },
        timeout: Duration(seconds: 600));

    autoSpeakWbSocket.connection.listen((v) {
      print('autoSpeakWbSocket connection  status: ${v}');
    });


    autoSpeakWbSocket.messages.listen((v) async {
      print('autoSpeak WbSocket message from server : ${v}');
      if (v is List<dynamic>) {
        print('value length:  ${v.length}');
        audioData = CommonUtil.combineUint8Lists(audioData, v as Uint8List);

        return;
      }
      if (v == 'ok') return;
      Map result = json.decode(v.toString());
      if(result['action'] == 'started') {

        //发送心跳包.
        ttsWsTimer = Timer.periodic(Duration(seconds: 7), (timer) {
          if (autoSpeakWbSocket != null) {
            autoSpeakWbSocket.send('Heartbeat'); //
          }

        });

        callBack.businessCallBack!(v);

      } else if (result['action'] == 'synthesizing') {
        print('autoSpeakWbSocket =====> end: ${result['end']}');
        if (result['end']) {
          Tips.dismissLoading();
          playAudioFromBytes(audioData);
          //播放完成后清空数据.
          audioData = Uint8List(0);
        }

      }

    });

    await autoSpeakWbSocket.connection.firstWhere((state) => state is ws.Connected);
  }



  void playAudioFromBytes(Uint8List data) async {
    player = AudioPlayer();
    // 将字节数据转换为 Uint8List
    await player?.play(BytesSource(data,mimeType: ''));
    stopTTSWs();
  }



  @override
  void onReady() {
    super.onReady();
    loadSomeRecords();
  }

  @override
  void onClose() {
    super.onClose();
    if (ttsWsTimer != null) {
      ttsWsTimer!.cancel();
    }

  }

  void loadSomeRecords() async {
    List<TranslationHistoryData> historyDatas = await DbDAOHelper().obtainTranslateHistoryList(AppConst.TRANSLATOIN_TYPE_DIRECT);
    if(historyDatas.length > 10) {
      historyDatas = historyDatas.sublist(0,19);
    }
    historyData.value = historyDatas;

    historyData.value.forEach((item) {
      historyWigetItem.add(Container(
        child: InkWell(
          onTap: () {
            historyItemChecked(item);
          },
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(item.raw_text,style: AppStyleThemeData.linkStyle,maxLines: 1,
                overflow: TextOverflow.ellipsis,),
              Text(item.translation,style: AppStyleThemeData.HINT_TEXT_STYLE,maxLines: 1,
                overflow: TextOverflow.ellipsis,)
            ],
          ),
        ),
      ),);
      historyWigetItem.add(SizedBox(height: 10.h));
    });

    if (historyDatas.length > 10) {
      historyWigetItem.add(Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          InkWell(
            onTap: () {
              Get.toNamed(Routes.HISTORY_RECORDS,parameters: {
                'source':'directTranslation'
              });
            },
            child: Container(
              margin: EdgeInsets.only(top: 10.h),
              child: Row(
                children: [
                  Image.asset('assets/images/icon_index_record.png',width: 16.w,height: 16.h),
                  SizedBox(width: 10.w),
                  Text('显示完整历史',style: AppStyleThemeData.linkStyle,maxLines: 1,
                    overflow: TextOverflow.ellipsis,)
                ],
              ),
            ),
          )

        ],
      ),);
    }

    if (historyDatas.length == 0) {
      historyWigetItem.add(Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            margin: EdgeInsets.only(top: 10.h),
            child: Row(
              children: [
                Text('无最近历史',style: AppStyleThemeData.linkStyle,maxLines: 1,
                  overflow: TextOverflow.ellipsis,)
              ],
            ),
          )

        ],
      ),);
    }

  }


  void historyItemChecked(TranslationHistoryData historyData) {
        audioService.fromLanguage = historyData.src_lang;
        audioService.toLanguage = historyData.tgt_lang;

        audioService.fromLanFlagDisplay.value = historyData.src_lang_display;
        audioService.toLanFlagDisplay.value = historyData.tgt_lang_display;


        audioService.indexPageFinalFromLanguage.value = historyData.raw_text;
        audioService.indexPageFinalToLanguage.value = historyData.translation;

        scrollToTop();

  }

  void scrollToTop () {
    Future.delayed(Duration(milliseconds: 200),() {
      // listScroll.jumpTo(0);
      listScroll.animateTo(
        0, // 目标位置（0 表示顶部）
        duration: Duration(milliseconds: 500), // 动画时长
        curve: Curves.easeInOut, // 动画曲线
      );
    });

  }



  void translationText2Text() async {
    if (audioService.indexPageFinalFromLanguage.value == '') {
      return;
    }

    if (audioService.indexPageFinalFromLanguage.value.length > 500) {

      Tips.showToast('文本翻译最大支持500字以内');
      return;
    }

    dio.Response resp = await dio.Dio(
    ).post(
      'https://xy-apis.newtranx.com/mt/v1/text',
      data: {
        "srcLang": audioService.fromLanguage,
        "tgtLang": audioService.toLanguage,
        "texts": [audioService.indexPageFinalFromLanguage.value]
      },
      options: dio.Options(
        responseType: dio.ResponseType.stream,
        headers: {
          'X-Api-Key': '264e03da4958e5ea405dd8f63b87da898757b821',
          'Content-Type': 'application/json'},
      ),

    );

   resp.data?.stream
        .cast<List<int>>()
        .transform(Utf8Decoder())
        .listen((event) {
              Map<String,dynamic> contentParams = json.decode(event);
              if (contentParams['code'] == 200) {
                audioService.indexPageFinalToLanguage.value = contentParams['data']['content'][0]['text'];
                taskId = contentParams['data']['taskId'];

                DbDAOHelper().saveTranslateHistory(audioService.fromLanguage,
                    audioService.toLanguage, audioService.indexPageFinalFromLanguage.value, audioService.indexPageFinalToLanguage.value, taskId!,AppConst.TRANSLATOIN_TYPE_DIRECT,
                audioService.fromLanFlagDisplay.value,audioService.toLanFlagDisplay.value);

              } else {
                audioService.indexPageFinalToLanguage.value = '翻译失败,请重新尝试.';
              }
        },
    );
  }

  void copySomething() async {
    try {
      await Clipboard.setData(ClipboardData(text: audioService.indexPageFinalToLanguage.value));
      // 可选：显示复制成功的反馈
      Tips.showToast('已复制');
    } on PlatformException catch (e) {
      debugPrint('复制失败: ${e.message}');
    }
  }

  void cleanContent() async {
    audioService.indexPageFinalFromLanguage.value = '';
    audioService.indexPageFinalToLanguage.value = '';

    IndexTranslationController index = Get.find<IndexTranslationController>();
    index.textEditingController.text = '';
    index.arrows_btn.value = false;

    IndexViewController indexController = Get.find<IndexViewController>();
    indexController.stopAudioPlay();



    Get.back();
  }


  void chooseFromLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': audioService.fromLanguage
    });
    audioService.fromLanguage = languageItem['code'];
    audioService.fromLanFlagDisplay.value = languageItem['desc'];

    translationText2Text();
  }

  void chooseToLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION, parameters: {
    'code': audioService.toLanguage
    });
    audioService.toLanguage = languageItem['code'];
    audioService.toLanFlagDisplay.value = languageItem['desc'];

    translationText2Text();
  }


  void audioSpeakerSource() {
   Tips.showLoading();
   initTTsWbSocket(DataCallBack(
        businessCallBack: (v) {
          autoSpeakWbSocket.send(json.encode(
              {
                'lang': audioService.fromLanguage,
                'text': audioService.indexPageFinalFromLanguage.value,
                'speed': 10/10,
                'male': true
              }
          ));
        }
    ));

  }

  void audioSpeakerTarget() {
    Tips.showLoading();
    initTTsWbSocket(DataCallBack(
        businessCallBack: (v) {
          autoSpeakWbSocket.send(json.encode(
              {
                'lang': audioService.toLanguage,
                'text': audioService.indexPageFinalToLanguage.value,
                'speed': 10/10,
                'male': true
              }
          ));
        }
    ));
  }


  void exchangeLanguages() {
     audioService.exchangeLanguages(callBack: DataCallBack(
       businessCallBack: (v) {
         // translationText2Text();
       }
     ));
  }

  void stopTTSWs () {
    if (autoSpeakWbSocket != null) {
      autoSpeakWbSocket!.send(json.encode({
        'end': true
      }));
      autoSpeakWbSocket!.close();
      autoSpeakWbSocket = null;
    }
    autoSpeakWbSocket = null;
  }

}
